package com.niuwa.p2p.service.impl.seal;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;

import com.niuwa.p2p.core.utils.FileUtil;
import com.niuwa.p2p.core.utils.ResourceLoader;
import com.niuwa.p2p.dao.nwfile.NWFileDao;
import com.niuwa.p2p.entity.nwfile.NWFile;
import com.niuwa.p2p.service.seal.SealPDFService;

/**
 * PDF签章
 * 通过SealSystem系统，调用sealAutoPdf接口，实施签章
 * 
 * SealSystem的webserviceURL地址：http://ip:port/Seal/services/SealService?wsdl
 * 
 * 1。取得需要签章PDF
 * 2。掉取SealSystem的webservice接口，实施签章
 * 3。取得签章好的PDF地址，存入文件系统。
 * 
 * @title SealPDFServiceImpl.java
 *
 * @author 计盛君
 * @version 1.0
 * @created 2015年5月3日
 */
public class SealPDFServiceImpl implements SealPDFService{

	
	private final static String WINDOWS_ENTER = "\r\n";
	
	private final static String LINUX_ENTER = "\n";
	
	private final static String TAB = "\t";
	
	private final static String SPACE = " ";
	
	private final static String EMPTY = "";
	
	@Autowired
	private static NWFileDao nwFileDao;
	
	@Override
	public boolean sealPDF(String fileId) throws Exception {
		
		// get fileName filePath from DB  (p2p_nwfile)
		NWFile nwFil = getFile(fileId);
		// createSoapXml
		String sealAutoPdfUrl = getSealAutoPdfUrl(nwFil);
		String sealedpdfUrl = connectSealSystemAndgetSealedPDF(sealAutoPdfUrl);
		//save pdf
		savePdf(sealedpdfUrl,"targeFile","targePath");
		return true;
	}	
	
//	private static NWFile getFilePath(String fileId) throws Exception{
//		NWFile nwFile = nwFileDao.getFile(fileId);
//		if (null == nwFile) {
//			throw new BusinessException("fileIsNotExist");
//		}
//		return nwFile;	
//	}
	
	private static NWFile getFile(String fileId) throws Exception{
		NWFile nwFile = new NWFile();
//		nwFile.setFileName("1.pdf");
//		nwFile.setFilePath("http://localhost:8080/niuwa-opr/pdf/tmp");	
		nwFile.setFileName("oprtest.pdf");
		nwFile.setFilePath("http://127.0.0.1:9231/Seal");
		return nwFile;
	}
		
	/**
	 * 从sealAutoPdfRequest.xml模板,创建sealAutoPdfRequest,准备传输用
	 * 
	 * @param nwFile
	 * @return
	 * @throws Exception
	 */
	private static String createXmlStr(NWFile nwFile) throws Exception{
		InputStream is = new  FileInputStream(new File(ResourceLoader.getPath("sealAutoPdfRequest.xml", SealPDFServiceImpl.class)));
		return FileUtil.inputStream2String(is,"UTF-8");
	}
	
	/**
	 * sealAutoPdfRequest模板里写入参数
	 * 1.文件名
	 * 2.文件Path
	 * 
	 * @param xmlStr
	 * @param nwFile
	 * @return
	 */
	// TODO use freemark to change 
	private static String writeParameters(String xmlStr, NWFile nwFile){
		return xmlStr.replaceAll("\\$fileNo", nwFile.getFileName()).replaceAll("\\$filePath", nwFile.getFilePath() + "/" + nwFile.getFileName());
	}
	
	/**
	 * 转换sealAutoPdfRequest.xml为一行,方便Http方式直接调用
	 * 
	 * @param xmlStr
	 * @return
	 */
	private static String replaceToOnline(String xmlStr){
		return xmlStr.replaceAll(WINDOWS_ENTER, EMPTY).replaceAll(LINUX_ENTER, EMPTY).replaceAll(TAB, EMPTY).replaceAll(SPACE, EMPTY);
	}
	
	private static String simpleEscapse(String xmlStr){
		return xmlStr.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("\"", "&quot;").replaceAll(" ", "&nbsp;");
	}
	private static String simpleDescapse(String xmlStr){
			
		return xmlStr.replaceAll("&amp;", "&").replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&quot;", "\"").replaceAll("&nbsp;", " ");
	} 
	
	private static String getSealAutoPdfUrl(NWFile nwFile) throws Exception{
		createXmlStr(nwFile);
		String url = "http://192.168.101.160:9231/Seal/services/SealService/sealAutoPdf?xmlStr=";
		// 设值参数
		String temp1 = writeParameters(createXmlStr(nwFile), nwFile);
		// 转换格式
		String temp2 = replaceToOnline(temp1);
		url = url + temp2;
		return url ;
	}
	
	public static String connectSealSystemAndgetSealedPDF(String url){

		Document doc = null;
		try {
			// TODO 处理 http statuscode and timeout
			doc = Jsoup.connect(url).timeout(5000).get(); // 设置延时5秒
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//System.out.println("Time is:"+ (System.currentTimeMillis() - start) + "ms");
		}
		//System.out.println(WebUtils.descape(doc.toString()));
		// TODO html escapse & desacpse  由于Seal系统的返回的特殊性，如下：
		/*
		 * <html>
		 *	 <head></head>
		 *	 <body>
		 *	  <ns:sealautopdfresponse xmlns:ns="http://serv">
		 *   <ns:return>
		 *	    &lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;SealDocResponse&gt; &lt;FILE_LIST&gt; &lt;TREE_NODE&gt; &lt;RET_CODE&gt;0&lt;/RET_CODE&gt; &lt;FILE_NAME&gt;oprtest.pdf&lt;/FILE_NAME&gt; &lt;FILE_MSG&gt;http://192.168.101.160:9231/Seal/doc/download.jsp?name=oprtest.pdf&lt;/FILE_MSG&gt; &lt;/TREE_NODE&gt; &lt;/FILE_LIST&gt; &lt;/SealDocResponse&gt; 
		 *	   </ns:return>
		 *	  </ns:sealautopdfresponse>
		 *	 </body>
		 *	</html>
		 * 
		 */
		String newDoc = simpleDescapse(doc.toString());
		Document doc2  = Jsoup.parse(newDoc);
		// TODO 根据result 判断
		String retCode = doc2.select("RET_CODE").text();	
		String fileName = doc2.select("FILE_NAME").text();		
		String fileMsg = doc2.select("FILE_MSG").text();		
		return fileMsg;
	}
	
	private void savePdf(String urlStr, String fileName, String savePath) throws IOException{
		FileUtil.httpUrl2File(urlStr, fileName, savePath); 
	}	
	
//	/**
//	 * 
//	 * @throws Exception
//	 */
//	public static void getJsoup() throws Exception {
//		NWFile nwFile = getFile("");
//
//		String url = "http://192.168.101.160:9231/Seal/services/SealService/sealAutoPdf?xmlStr=";
//		String temp1 = writeParameters(createXmlStr(nwFile), nwFile);
//		String temp2 = replaceToOnline(temp1);		
//		System.out.println(temp2);
//		url = url + temp2;
//		long start = System.currentTimeMillis();
//		Document doc = null;
//		try {
//			// TODO 处理 http statuscode and timeout
//			doc = Jsoup.connect(url).timeout(5000).get(); // 设置延时5秒
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			System.out.println("Time is:"+ (System.currentTimeMillis() - start) + "ms");
//		}
//		//System.out.println(WebUtils.descape(doc.toString()));
//		// TODO html escapse & desacpse
//		String newDoc = simpleDescapse(doc.toString());
//		System.out.println(doc.toString());
//		Document doc2  = Jsoup.parse(newDoc);
//		String retCode = doc2.select("RET_CODE").text();
//		System.out.println(retCode);
//		String fileName = doc2.select("FILE_NAME").text();
//		System.out.println(fileName);
//		String fileMsg = doc2.select("FILE_MSG").text();
//		System.out.println(fileMsg);				
//	}	
//	
//	public static void main(String[] args){
//		
//		try {
////			NWFile nwFile = getFilePath("");
////			createXmlStr(nwFile);
//			getJsoup();
//			//doseal();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
}
